import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

public class UserInformationFetcher {
	Client client;
	public UserInformationFetcher(Client client) {
		this.client = client;
	}
	
	public void fetch() {
		String urlString = "http://api.twitter.com/1/users/show.xml?user_id="+ client.user.id;
		try {
			URL url = new URL(urlString);
			Downloader downloader = new Downloader(url);
			String xml = downloader.fetchAsString();
			HashMap<String, String> userData = parse(xml);
			client.handleUserDataResults(userData);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	private HashMap<String, String> parse(String string) {
		if(string == null) return null;
		
		HashMap<String, String> data = new HashMap<String, String>();

		CustomXpath cx 		= new CustomXpath(string);
		String name 		= cx.getFirstTextContent("/user/name/text()");
		String screen_name 	= cx.getFirstTextContent("/user/screen_name/text()");
		String location 	= cx.getFirstTextContent("/user/location/text()");
		String description 	= cx.getFirstTextContent("/user/description/text()");
		String url 			= cx.getFirstTextContent("/user/url/text()");
		
		data.put("name", name);
		data.put("screen_name", screen_name);
		data.put("location", location);
		data.put("description", description);
		data.put("url", url);
		
		System.out.println(" + Fetched users information");
		
		return data;
	}
}
